package main

import (
	"flag"
	"fmt"
	"net"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/lichenxin/grpc-consul-server/pkg/pb"
	"gitee.com/lichenxin/grpc-consul-server/pkg/room"
	"gitee.com/lichenxin/grpc-consul-server/pkg/utils"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	v1 "google.golang.org/grpc/health/grpc_health_v1"
)

var (
	host string
	port int
)

func init() {
	flag.IntVar(&port, "port", 0, "port")
	flag.Parse()

	var err error
	host, err = utils.GetLocalIP()
	if err != nil {
		panic(errors.WithStack(err))
	}

	if port <= 0 {
		port = utils.RandInt(8000, 9000)
	}

	logrus.SetFormatter(&logrus.JSONFormatter{})
}

func main() {
	s := grpc.NewServer()

	signWatcher := make(chan os.Signal)
	signal.Notify(signWatcher, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)

	address := fmt.Sprintf("%s:%d", host, port)
	listen, err := net.Listen("tcp", address)
	if err != nil {
		logrus.WithError(err).WithField("address", address).Panic("tcp listen")
	}

	m := room.GetServer()
	pb.RegisterRoomServer(s, m)
	v1.RegisterHealthServer(s, health.NewServer())
	if err := m.Register(port); err != nil {
		logrus.WithError(err).Panic("register server")
	}

	go func() {
		<-signWatcher
		m.Stop()
		s.Stop()
	}()

	logrus.WithField("address", address).Info("start server")
	if err = s.Serve(listen); err != nil {
		logrus.WithError(err).WithField("listen", address).Panic("start server")
	}
}
